import {Button, Divider, message, Popconfirm} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import {TableListItem} from './data.d';
import {remove, batchRemove, list} from './service';
import {AuthConsumer} from '@/utils/authContent'
import DetailForm from "./components/DetailForm";


/**
 * 删除
 * @param record
 */
const handleRemove = async (record: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    const data = await remove(record.logId);
    hide();
    if (data.code === 1) {
      message.success('删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
  message.error('删除失败，请重试');
  return false;
};

/**
 *  批量删除
 * @param selectedRows
 */
const handleBatchRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在批量删除');
  if (!selectedRows) return true;
  try {
    const logIds = new Array();
    selectedRows.forEach((row: TableListItem) => {
      logIds.push(row.logId);
    })
    const data = await batchRemove(logIds);
    hide();
    if (data.code === 1) {
      message.success('批量删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('批量删除失败，请重试');
    return false;
  }
  message.error('批量删除失败，请重试');
  return false;
};


const LogTableList: React.FC<{}> = () => {

  // 详情Model可见性
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  // 设置详情表单值
  const [detailFormValues, setDetailFormValues] = useState({});
  // 通过actionRef进行表单刷新
  const actionRef = useRef<ActionType>();
  //  选择行数据的状态
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  // 删除确认按钮
  const onRemoveConfirm = async (record: TableListItem) => {
    await handleRemove(record);
    actionRef.current?.reloadAndRest?.();
  }

  // 表头
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'logId',
      valueType: 'textarea',
      hideInForm: true,
      align: "center",
    },
    {
      title: '用户名',
      dataIndex: 'username',
      valueType: 'text',
      align: "center",
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      valueType: 'text',
      copyable: true,
      align: "center",
    },
    {
      title: '模块名称',
      dataIndex: 'moduleName',
      valueType: 'text',
      align: "center",
    },
    {
      title: '用户操作',
      dataIndex: 'operation',
      valueType: 'text',
      align: "center",
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
      ellipsis: true,
      align: "center",
    },
    {
      title: '响应时间',
      dataIndex: 'time',
      valueType: 'text',
      hideInSearch: true,
      align: "center",
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      valueType: 'dateTime',
      align: "center",
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: "center",
      render: (_, record) => (
        <>
          <AuthConsumer name={'base:dict:update'}>
            <a onClick={() => {
              handleDetailModalVisible(true);
              setDetailFormValues(record);
            }}
            >详情</a>
          </AuthConsumer>
          <AuthConsumer name={'base:log:remove'}>
            <Divider type="vertical"/>
            <Popconfirm
              title="确认需要删除"
              okText="确定"
              cancelText="取消"
              onConfirm={() => onRemoveConfirm(record)}
            >
              <a href="#">删除</a>
            </Popconfirm>
          </AuthConsumer>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      {/* 表格 */}
      <ProTable<TableListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="logId"
        search={{
          labelWidth: 120,
        }}
        // request = {async (params, sorter, filter) => {
        request={async (params) => {
          console.log(params)
          const data = await list({...params});
          if (data.code === 1) {
            return {
              data: data.data.rows,
              // success请返回true，不然table会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: data.data.total,
            };
          }
          return {
            data: [],
            success: true,
            total: 0,
          }
        }
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />

      {/* 选择数据的状态 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <AuthConsumer name={'base:log:batchRemove'}>
            <Button danger type={"primary"}
                    onClick={async () => {
                      await handleBatchRemove(selectedRowsState);
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }}
            >
              批量删除
            </Button>
          </AuthConsumer>
        </FooterToolbar>
      )}

      {/* 详情表单 */}
      <DetailForm
        detailModalVisible={detailModalVisible}
        handleDetailModalVisible={handleDetailModalVisible}
        detailFormValues={detailFormValues}
        actionRef={actionRef}
      ></DetailForm>

    </PageContainer>
  );
};

export default LogTableList;
